package com.loop.nio;

import java.net.InetSocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * Scattering 将数据写入到buffer时，可以采用buffer数组，依次写入【分散】
 * Gathering 从buffer中读取数据时，可以采用buffer数组，依次读取【聚集】
 *
 * @author zhangxiaolu
 * @since 2023-09-03 21:39
 */
public class ScatteringAndGatheringTest {

    public static void main(String[] args) throws  Exception {

        // 使用 ServerSocketChannel 和 SocketChannel 网络
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(8090);

        // 绑定端口到socket，并启动
        serverSocketChannel.socket().bind(inetSocketAddress);

        // 创建Buffer数组
        ByteBuffer[] byteBuffers = new ByteBuffer[2];
        byteBuffers[0] = ByteBuffer.allocate(5);
        byteBuffers[1] = ByteBuffer.allocate(3);

        // 等待客户端连接 （telnet）
        System.out.println("Waiting for a client ...");
        SocketChannel socketChannel = serverSocketChannel.accept();
        int messageLen = 8;
        // 接收客户端数据到buffer，循环的读取
        while (true) {
            int byteRead = 0;
            while (byteRead < messageLen) {
                long l = socketChannel.read(byteBuffers);
                byteRead += l;// 累计读取的字节数
                System.out.println("byteRead = " + byteRead);
                // 使用流打印，看看当前buffer的postion和limit
                Arrays.stream(byteBuffers).map(buffer ->
                        "position = " + buffer.position() + ", limit = " + buffer.limit()).forEach(System.out::println);

            }

            // 将所有的buffer进行filp
            Arrays.asList(byteBuffers).forEach(Buffer::flip);
            // 将数据读出显示到客户端
            long byteWrite = 0;
            while (byteWrite < messageLen) {
                long l = socketChannel.write(byteBuffers);
                byteWrite += l;
                System.out.println("byteWrite = " + byteWrite);
            }
            // 重置buffer
            Arrays.asList(byteBuffers).forEach(Buffer::clear);

            System.out.println("byteRead = " + byteRead + ", byteWrite = " + byteWrite + ", messageLen = " + messageLen);
        }
    }
}
